import json


def Wlog(fileP, msg, method, addtime=True):
    '''写日志
    @param fileP [str] 文件路径，没有此目录会自动创建
    @param msg [str] 写入的信息
    @param method [str] 文件写入方式 w:覆盖 a:追加
    @author Tan<smallcatx0@gmail.com>
    '''
    import os
    import time
    fileDir = os.path.dirname(fileP)
    fileDir.strip()
    # 父目录不存在则创建父目录
    if (fileDir != '') and (not os.path.exists(fileDir)):
        os.makedirs(fileDir)
    if(addtime):
        nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        msg = nowtime + '=>' + msg
    msg += '\n'
    with open(fileP, method, encoding='utf-8') as fp:
        fp.write(msg)


def rJson(fielPath):
    '''加载json配置文件
    @param fileP [str] 文件路径，没有此目录会自动创建
    @author Tan<smallcatx0@gmail.com>
    '''
    with open(fielPath, "r", encoding="utf-8") as fp:
        con = json.load(fp)
    return con

def wJson(fielPath, dat):
    with open(fielPath, 'w') as fp:
        json.dump(dat, fp)

# 读取单行配置文件


def Ltxt(fielPath):
    listCon = set()
    with open(fielPath, "r", encoding="utf-8") as fp:
        oneLine = True
        while oneLine:
            oneLine = fp.readline()
            line = oneLine.strip()  # 去除两边的空格
            # 如果是注释，整行都不要了
            if line == '' or ';' == line[0]:
                continue
            if '#' == line[0] or '；' == line[0]:
                continue
            line = line.strip('\r')
            line = line.strip('\n')
            line = line.split(';')[0]   # 去除同行注释
            line = line.split('#')[0]   # 去除同行注释
            line = line.split('；')[0]   # 去除同行注释
            if line != '':
                listCon.add(line)
    return list(listCon)

# 读取ini格式的配置文件


def iniConf(fielPath):
    conf = {}
    confList = Ltxt(fielPath)
    for one in confList:
        temp = one.split('=')
        if len(temp) < 2:
            continue
        k = temp[0].strip()
        v = temp[1].strip()
        if k in conf:
            if isinstance(conf[k], list):
                conf[k].append(v)
                continue
            oldv = conf[k]
            conf[k] = [oldv, v]
        else:
            conf[k] = v
    return conf


if __name__ == "__main__":
    res = iniConf('adv_spy.ini')
    print(res)
